package com.example.chuqq.gpssigninapplication.controller;

import android.util.Log;

import com.example.chuqq.gpssigninapplication.model.UserData;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by chuqq on 2017/11/26.
 *
 * 和服务器交互工具类。
 * 规范：尽量使用form，而不是json
 */

public class Rest {
    final static private String TAG = "Rest";
    final static private String SERVER_ADDR = "http://mp.xxying.com:8091/gpssignin"; // "http://192.168.1.107:8091/gpssignin"
    final static private String URL_REGISTER = "/register";
    final static private String URL_LOGIN = "/login";
    final static private String URL_UPLOAD_GPS = "/gps";

    /**
     * 注册
     * 返回是否成功
      */
    public static boolean register(String phone, String name, String password) {
        Log.i(TAG, "注册 register(): phone: " + phone + ", name: " + name + ", password: " + password);
        String url = SERVER_ADDR + URL_REGISTER;

        try {
            // 发送http请求
            OkHttpClient client = new OkHttpClient();

            RequestBody body = new FormBody.Builder()
                    .add("phone", phone)
                    .add("name", name)
                    .add("password", password)
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();

            Response response = client.newCall(request).execute();
            if (!response.isSuccessful() || response.code() != 200) {
                Log.e(TAG, "register error: " + response);
                return false;
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 登录
     * 返回UserData，包含用户信息。如果登录失败，返回null
      */
    public static UserData login(String phone, String password) {
        Log.i(TAG, "登录 login(): phone: " + phone + ", password: " + password);
        String url = SERVER_ADDR + URL_LOGIN;

        try {
            // 发送http请求
            OkHttpClient client = new OkHttpClient();

            RequestBody body = new FormBody.Builder()
                    .add("phone", phone)
                    .add("password", password)
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();

            Response response = client.newCall(request).execute();
            if (!response.isSuccessful() || response.code() != 200) {
                Log.e(TAG, "login error: " + response);
                return null;
            }

            UserData userData = new Gson().fromJson(response.body().string(), UserData.class);
            Log.i(TAG, "userData: " + userData);
            return userData;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

//        UserData userData = new UserData(null);
//        userData.setName("chuqq");
//        userData.setPhone("13770641012");
//        userData.setPassword("580608");
//        userData.setToken("chuqq token");
//        return userData;
    }

    /**
     * 上传GPS
     * 返回是否上传成功
      */
    public static void uploadGPS(UserData userData, double lon, double lat) {
        final String url = SERVER_ADDR + URL_UPLOAD_GPS;

        if (lon < 1 || lon > 300 || lat < 1 || lat > 300) {
            Log.d(TAG, "location invalid");
            return;
        }

        Log.i(TAG, "上传GPS uploadGPS(): phone: " + userData.getPhone() + ", lon: " + lon + ", lat: " + lat);
        try {
            // 发送http请求
            OkHttpClient client = new OkHttpClient();
            FormBody.Builder formBuilder = new FormBody.Builder();
            formBuilder.add("phone", userData.getPhone());
            formBuilder.add("password", userData.getPassword());
            formBuilder.add("lat", ""+lat);
            formBuilder.add("lon", ""+lon);
            FormBody body = formBuilder.build();

            Request request = new Request.Builder()
                    .url("http://mp.xxying.com:8091/gpssignin/gps?phone="+userData.getPhone()+"&password="+userData.getPassword()+"&lat=" + lat + "&lon=" + lon)
//                        .url("http://192.168.1.106:8091/gpssignin/gps?lat=" + lat + "&lon=" + lon)
                    .post(body)
                    .build();

            Call call = client.newCall(request);
            Log.d(TAG, "call.enqueue");
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String result = response.body().string();
                    Log.i("GPSApp", "res: " + result);
                }
            });
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }
}
